#include <syslog.h>
#include <stdarg.h>
#include <string.h>
#include "logger.h"
#include <stdio.h>

#define	LOG_BUF_SIZE	2048

CSysLog::CSysLog(void)
{
    m_nLevel=MSG_ALL;
    m_bOpen=false;
    pthread_mutex_init(&m_Lock,0);
}

CSysLog::~CSysLog(void)
{
    Close();
    pthread_mutex_destroy(&m_Lock);
}
void CSysLog::Open(int level,char* ident,int facility)
{
    pthread_mutex_lock(&m_Lock);
    if(m_bOpen) {pthread_mutex_unlock(&m_Lock);return;}
    m_nLevel=level;
    if(facility>=0)
//	openlog(ident,LOG_PID,(facility+16)<<3);
	openlog(ident,LOG_PID,facility);
    else openlog(ident,LOG_PID,LOG_SYSLOG);
    m_bOpen=true;
    pthread_mutex_unlock(&m_Lock);
}
void CSysLog::Log(int level,char* fmt,...)
{
    pthread_mutex_lock(&m_Lock);
    if(!m_bOpen || level>m_nLevel) {pthread_mutex_unlock(&m_Lock);return;}
    va_list ap;
    char buf[LOG_BUF_SIZE];
    va_start(ap,fmt);
    vsnprintf(buf,LOG_BUF_SIZE,fmt,ap);
    va_end(ap);
    for(char* ptr=buf;*ptr;ptr++) if(*ptr=='\r' || *ptr=='\n') *ptr='.';
    syslog(LOG_INFO,buf);
    pthread_mutex_unlock(&m_Lock);
}
void CSysLog::Close(void)
{
    pthread_mutex_lock(&m_Lock);
    if(!m_bOpen) {pthread_mutex_unlock(&m_Lock);return;}
    m_bOpen=false;
    closelog();
    pthread_mutex_unlock(&m_Lock);
}
